package com.sanjin.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @description: 加密工具类
 * @author: sanjin
 * @date: 2019.3.12
 */
public class EncryptUtils {

    // 用于 sha1 加密
    private static final char[] HEX = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * byte[]字节数组 转换成 十六进制字符串
     *
     * @param arr 要转换的byte[]字节数组
     *
     * @return  String 返回十六进制字符串
     */
    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; ++i) {
            sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * 普通md5加密
     * @param plaintext
     * @return
     */
    public static String md5(String plaintext) {
        String ciphertext = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.update(plaintext.getBytes());
            ciphertext = hex(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            System.out.println("加密失败");
            e.printStackTrace();
        }
        return ciphertext;
    }



    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String sha1(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        StringBuilder stringBuilder = new StringBuilder(5);

        System.out.println(stringBuilder);
        stringBuilder.append(":dklsajlad:");
        System.out.println(stringBuilder);

    }
}
